/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.gateway.handler.predicate;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.cloud.gateway.event.WeightDefinedEvent;
import org.springframework.cloud.gateway.support.WeightConfig;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.web.server.ServerWebExchange;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.WEIGHT_ATTR;

/**
 * @author Spencer Gibb
 * <p>
 *     WeightRoutePredicateFactory 是 Spring Cloud Gateway 中的一个具体实现类，用于定义 基于权重的路由谓词。它的作用是根据请求被分配到的权重组和权重值来决定是否匹配该路由。以下是对其功能、设计和使用场景的详细解析。
 *
 * 1. 核心功能
 * 1.1 路由匹配逻辑
 * WeightRoutePredicateFactory 的核心逻辑是：
 * 检查请求是否属于某个权重组。
 * 如果请求已经通过 WeightCalculatorWebFilter 分配了权重，则判断当前路由是否与分配的路由 ID 匹配。
 * 如果匹配，则返回 true，表示请求匹配该路由；否则返回 false。
 * 1.2 权重分配机制
 * 权重分配逻辑由 WeightCalculatorWebFilter 完成：
 * 根据配置的权重比例，随机生成一个数值并分配给某个路由。
 * 将分配结果存储在 ServerWebExchange 的属性中（键为 WEIGHT_ATTR）。
 * 谓词工厂从属性中读取权重分配结果，并检查当前路由是否匹配。
 * 1.3 配置支持
 * 它继承了 AbstractRoutePredicateFactory，并实现了快捷配置支持。
 * 通过 shortcutFieldOrder 和 shortcutFieldPrefix 方法定义了快捷配置的字段顺序和前缀，允许用户以简化的形式定义参数。
 * 1.4 事件发布
 * 在应用谓词之前，会发布一个 WeightDefinedEvent 事件，通知其他组件权重配置已定义。
 *
 * 示例：
 * spring:
 *   cloud:
 *     gateway:
 *       routes:
 *         - id: example_route_1
 *           uri: http://example.org
 *           predicates:
 *             - Weight=group1, 80
 *         - id: example_route_2
 *           uri: http://example.com
 *           predicates:
 *             - Weight=group1, 20
 * </p>
 */
// TODO: make this a generic Choose out of group predicate?
public class WeightRoutePredicateFactory extends AbstractRoutePredicateFactory<WeightConfig>
		implements ApplicationEventPublisherAware {

	/**
	 * Weight config group key.
	 */
	public static final String GROUP_KEY = WeightConfig.CONFIG_PREFIX + ".group";

	/**
	 * Weight config weight key.
	 */
	public static final String WEIGHT_KEY = WeightConfig.CONFIG_PREFIX + ".weight";

	private static final Log log = LogFactory.getLog(WeightRoutePredicateFactory.class);

	private ApplicationEventPublisher publisher;

	public WeightRoutePredicateFactory() {
		super(WeightConfig.class);
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList(GROUP_KEY, WEIGHT_KEY);
	}

	@Override
	public String shortcutFieldPrefix() {
		return WeightConfig.CONFIG_PREFIX;
	}

	@Override
	public void beforeApply(WeightConfig config) {
		if (publisher != null) {
			publisher.publishEvent(new WeightDefinedEvent(this, config));
		}
	}

	@Override
	public Predicate<ServerWebExchange> apply(WeightConfig config) {
		return new GatewayPredicate() {
			@Override
			public boolean test(ServerWebExchange exchange) {
				Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR, Collections.emptyMap());

				String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR);

				// all calculations and comparison against random num happened in
				// WeightCalculatorWebFilter
				String group = config.getGroup();
				if (weights.containsKey(group)) {

					String chosenRoute = weights.get(group);
					if (log.isTraceEnabled()) {
						log.trace("in group weight: " + group + ", current route: " + routeId + ", chosen route: "
								+ chosenRoute);
					}

					return routeId.equals(chosenRoute);
				}
				else if (log.isTraceEnabled()) {
					log.trace("no weights found for group: " + group + ", current route: " + routeId);
				}

				return false;
			}

			@Override
			public Object getConfig() {
				return config;
			}

			@Override
			public String toString() {
				return String.format("Weight: %s %s", config.getGroup(), config.getWeight());
			}
		};
	}

}
